package com.lyc.campuslife.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.lyc.campuslife.commonService.EmailService;
import com.lyc.campuslife.dto.LoginFormDTO;
import com.lyc.campuslife.dto.Result;
import com.lyc.campuslife.dto.UserDTO;
import com.lyc.campuslife.entity.User;
import com.lyc.campuslife.mapper.UserMapper;
import com.lyc.campuslife.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyc.campuslife.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.lyc.campuslife.utils.RedisConstants.*;
import static com.lyc.campuslife.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lyc
 * @since 2024-05-07
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private EmailService emailService;

    @Override
    public Result sendCode(String email){
        if (RegexUtils.isEmailInvalid(email)) {
            return Result.fail("邮箱格式不正确");
        }
        //阻止短时间重复请求验证码
        String oldCode = stringRedisTemplate.opsForValue().getAndExpire(LOGIN_CODE_KEY + email, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        if (oldCode != null) {
            return Result.ok(oldCode);
        }
        String code = RandomUtil.randomString(6);
        boolean sent = emailService.sendLoginCode(email, code);
        if (sent)
            stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + email, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        log.info("发送登录验证码：{}", code);
        return Result.ok(code);
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        // 1.校验邮箱
        String email = loginForm.getEmail();
        if (RegexUtils.isEmailInvalid(email)) {
            // 2.如果不符合，返回错误信息
            return Result.fail("邮箱格式错误！");
        }
        // 3.校验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + email);
        String code = loginForm.getCode();
        if (cacheCode == null || !cacheCode.equals(code)) {
            //3.不一致，报错
            return Result.fail("验证码错误");
        }
        //一致，查询用户
        User user = query().eq("email", email).one();
        //5.判断用户是否存在
        if (user == null) {
            //不存在，则创建
            user = createUser(email);
        }
        //7.保存用户信息到redis中
        //生成token
        String token = UUID.randomUUID().toString(true);
        //将user对象转为hashmap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        //存储 redis
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        //设置有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        //登陆成功则删除验证码信息
        stringRedisTemplate.delete(LOGIN_CODE_KEY + email);
        //返回token
        return Result.ok(token);
    }

    @Override
    public Result sign(Long id) {
        //1. 获取日期
        LocalDateTime now = LocalDateTime.now();
        //2. 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + id + keySuffix;
        //3. 获取今天是当月第几天(1~31)
        int dayOfMonth = now.getDayOfMonth();
        //4. 写入Redis  BITSET key offset 1
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return Result.ok();
    }

    @Override
    public Result signCount(Long userId) {
        //1. 获取日期
        LocalDateTime now = LocalDateTime.now();
        //2. 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //3. 获取今天是当月第几天(1~31)
        int dayOfMonth = now.getDayOfMonth();
        //4. 获取截止至今日的签到记录  BITFIELD key GET uDay 0
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create()
                .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (result == null || result.isEmpty()) {
            return Result.ok(0);
        }
        //5. 循环遍历
        int count = 0;
        Long num = result.get(0);
        while (true) {
            if ((num & 1) == 0) {
                break;
            } else
                count++;
            //数字右移，抛弃最后一位
            num >>>= 1;
        }
        return Result.ok(count);
    }
    private User createUser(String email) {
        User user = new User();
        user.setEmail(email);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(6));
        save(user);
        return user;
    }
}
